<template>
  <div class="box">
    <h1>用户B</h1>
    <div class="container">
      <video id="videoB" ref="videoB" autoplay playsinline></video>
      <div class="container-small">
        <video id="videoBSmall" ref="videoBSmall" autoplay playsinline></video>
      </div>
      <div id="layerB" class="layer" ref="layerB">
        <div class="layer__text">用户A邀请你视频通话...</div>
        <div id="hangupLayer" class="layer" ref="hangupLayer">
          <div class="layer__text">通话已挂断</div>
        </div>
        <div class="layer__btns">
          <button id="callBtn" class="layer__btn" @click="answerCall" ref="callBtn">接听</button>
          <button id="hangupBtn" class="layer__btn" @click="hangupCall" ref="hangupBtn">挂断</button>
        </div>
      </div>
    </div>
    <div class="footer">
      <button id="hangupBtn" @click="hangupCall" class="hangup-btn">挂断</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onUnmounted, onMounted } from 'vue';
import { useMainStore } from '../store/index';
import { useMessage } from 'naive-ui';
const messageBox = useMessage()
const store: any = useMainStore();
const socket = store.socket
const roomId = store.sender.Id; // 房间号

const videoB = ref<HTMLVideoElement | null>(null);
const videoBSmall = ref<HTMLVideoElement | null>(null);
const layerB = ref<HTMLDivElement | null>(null);
const callBtn = ref<HTMLButtonElement | null>(null);
const hangupBtn = ref<HTMLButtonElement | null>(null);
const hangupLayer = ref<HTMLDivElement | null>(null);
let streamB: MediaStream | null = null;
let peer: RTCPeerConnection | null = null;

onMounted(() => {
  hangupLayer.value!.style.display = 'none';
});

socket.on('offerEvent', async (offer: RTCSessionDescriptionInit) => {
  try {
    if (!peer) {
      peer = new RTCPeerConnection();
      peer.onicecandidate = event => event.candidate && socket.emit('candidateEvent', { roomId, candidate: event.candidate });
      peer.ontrack = event => {
        if (layerB.value && callBtn.value && hangupBtn.value && videoBSmall.value) {
          layerB.value.style.display = 'none'; // 隐藏 layerB
          callBtn.value.style.display = 'none';
          hangupBtn.value.style.display = 'inline-block';
          videoBSmall.value.srcObject = event.streams[0];
          videoBSmall.value.play();
        }
      };
    }

    if (streamB) {
      streamB.getTracks().forEach(track => peer!.addTrack(track, streamB!));
    }

    await peer.setRemoteDescription(offer);
    const answer = await peer.createAnswer();
    await peer.setLocalDescription(answer);
    socket.emit('answerEvent', { roomId, answer });
  } catch (error) {
    console.error('处理offer失败:', error);
  }
})
socket.on('end', () => {
  console.log("接受方收到挂断消息")
  if (hangupLayer.value) {
    messageBox.info(
       '对方已挂断视频通话')
    console.log("设置 hangupLayer 显示")
    store.isVideoReciverShow = false;
    hangupLayer.value.style.display = 'flex'; // 显示 hangupLayer
  } else {
    console.error("hangupLayer 为空")
  }
  closeStream();
})
const answerCall = async () => {
  try {
    socket.emit('acceptCallEvent', roomId);
    layerB.value!.style.display = 'none'; // 隐藏 layerB
    streamB = await getLocalStream();
    if (streamB) {
      videoB.value!.srcObject = streamB;
      videoB.value!.play();
      if (videoBSmall.value) {
        videoBSmall.value.srcObject = streamB; // 将本地视频流赋值给 videoBSmall
        videoBSmall.value.play();
      }
    }
  } catch (error) {
    console.error('接听失败:', error);
  }
};
const hangupCall = () => {
  try {
    if (peer) {
      peer.close();
      peer = null;
    }
    closeStream();
    store.isVideoReciverShow = false;
    console.log(roomId)
    socket.emit('end', roomId, (error: any) => {
      if (error) {
        console.error('Error emitting end event:', error);
      }
    })
  } catch (error) {
    console.error(error);
  }
};

const getLocalStream = async () => {
  try {
    return await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
  } catch (error) {
    console.error('获取本地音视频流失败:', error);
    return null;
  }
};

const closeStream = () => {
  if (streamB) {
    streamB.getTracks().forEach(track => track.stop());
    streamB = null;
  }
  if (videoB.value) {
    videoB.value.srcObject = null;
  }
  if (videoBSmall.value) {
    videoBSmall.value.srcObject = null;
  }
};
onUnmounted(() => {
  hangupCall();
  // socket.disconnect();
});
</script>

<style scoped lang="less">
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  background-color: #f5f5f5;
}

.box {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  width: 100%;
  max-width: 400px;

  h1 {
    margin: 20px 0;
    display: flex;
    justify-content: center;
    width: 100%;
  }
}

.container {
  width: 100%;
  height: 480px;
  background-color: #000;
  position: relative;
  overflow: hidden;
  border-radius: 10px 10px 0 0;

  video {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .container-small {
    width: 120px;
    height: 160px;
    position: absolute;
    right: 10px;
    bottom: 10px;
    z-index: 1;
    border-radius: 5px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }

  .layer {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 2;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.8);
    color: #fff;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    &__text {
      font-size: 18px;
      margin-bottom: 20px;
    }

    &__btns {
      display: flex;
      gap: 20px;
    }

    &__btn {
      width: 120px;
      height: 48px;
      cursor: pointer;
      background-color: #4caf50;
      border: none;
      border-radius: 24px;
      color: #fff;
      font-size: 16px;
      font-weight: bold;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
      transition: background-color 0.3s, transform 0.3s;

      &:hover {
        background-color: #66bb6a;
        transform: scale(1.05);
      }

      &:active {
        background-color: #388e3c;
        transform: scale(0.95);
      }

      &#hangupBtn {
        background-color: #ff4d4f;

        &:hover {
          background-color: #ff7875;
        }

        &:active {
          background-color: #d9363e;
        }
      }
    }
  }
}

.footer {
  display: flex;
  justify-content: center;
  padding: 20px 0;
  width: 100%;

  .hangup-btn {
    width: 120px;
    height: 48px;
    cursor: pointer;
    background-color: #ff4d4f;
    border: none;
    border-radius: 24px;
    color: #fff;
    font-size: 16px;
    font-weight: bold;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    transition: background-color 0.3s, transform 0.3s;

    &:hover {
      background-color: #ff7875;
      transform: scale(1.05);
    }

    &:active {
      background-color: #d9363e;
      transform: scale(0.95);
    }
  }
}
</style>